package com.example.managemyself.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.example.managemyself.util.OpenWeatherHelper;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 天气数据缓存管理器
 * 实现每小时缓存天气数据，避免频繁API请求
 */
public class WeatherCacheManager {
    
    private static final String TAG = "WeatherCacheManager";
    private static final String PREF_NAME = "weather_cache";
    private static final String KEY_WEATHER_DATA = "weather_data";
    private static final String KEY_CACHE_TIME = "cache_time";
    private static final String KEY_CITY_NAME = "city_name";
    
    // 缓存有效期：1小时（毫秒）
    private static final long CACHE_DURATION = 60 * 60 * 1000; // 1小时
    
    private static WeatherCacheManager instance;
    private SharedPreferences sharedPreferences;
    private Context context;
    
    public static synchronized WeatherCacheManager getInstance(Context context) {
        if (instance == null) {
            instance = new WeatherCacheManager(context.getApplicationContext());
        }
        return instance;
    }
    
    private WeatherCacheManager(Context context) {
        this.context = context;
        this.sharedPreferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
    }
    
    /**
     * 获取缓存的天气数据
     * @param cityName 城市名称
     * @return 如果缓存有效返回天气数据，否则返回null
     */
    public OpenWeatherHelper.WeatherInfo getCachedWeather(String cityName) {
        try {
            String cachedCityName = sharedPreferences.getString(KEY_CITY_NAME, "");
            long cacheTime = sharedPreferences.getLong(KEY_CACHE_TIME, 0);
            String weatherDataJson = sharedPreferences.getString(KEY_WEATHER_DATA, "");
            
            // 检查城市是否匹配
            if (!cityName.equals(cachedCityName)) {
                Log.d(TAG, "城市不匹配，缓存无效: " + cachedCityName + " vs " + cityName);
                return null;
            }
            
            // 检查缓存是否过期
            long currentTime = System.currentTimeMillis();
            if (currentTime - cacheTime > CACHE_DURATION) {
                Log.d(TAG, "缓存已过期，需要重新获取天气数据");
                return null;
            }
            
            // 解析缓存的天气数据
            if (!weatherDataJson.isEmpty()) {
                OpenWeatherHelper.WeatherInfo weatherInfo = parseWeatherFromJson(weatherDataJson);
                if (weatherInfo != null) {
                    Log.d(TAG, "使用缓存的天气数据: " + cityName);
                    return weatherInfo;
                }
            }
            
        } catch (Exception e) {
            Log.e(TAG, "获取缓存天气数据失败", e);
        }
        
        return null;
    }
    
    /**
     * 缓存天气数据
     * @param cityName 城市名称
     * @param weatherInfo 天气信息
     */
    public void cacheWeather(String cityName, OpenWeatherHelper.WeatherInfo weatherInfo) {
        try {
            String weatherDataJson = convertWeatherToJson(weatherInfo);
            long currentTime = System.currentTimeMillis();
            
            sharedPreferences.edit()
                    .putString(KEY_CITY_NAME, cityName)
                    .putLong(KEY_CACHE_TIME, currentTime)
                    .putString(KEY_WEATHER_DATA, weatherDataJson)
                    .apply();
            
            Log.d(TAG, "天气数据已缓存: " + cityName + " at " + new java.util.Date(currentTime));
            
        } catch (Exception e) {
            Log.e(TAG, "缓存天气数据失败", e);
        }
    }
    
    /**
     * 检查缓存是否有效
     * @param cityName 城市名称
     * @return true如果缓存有效，false如果需要重新获取
     */
    public boolean isCacheValid(String cityName) {
        String cachedCityName = sharedPreferences.getString(KEY_CITY_NAME, "");
        long cacheTime = sharedPreferences.getLong(KEY_CACHE_TIME, 0);
        
        // 检查城市是否匹配
        if (!cityName.equals(cachedCityName)) {
            return false;
        }
        
        // 检查缓存是否过期
        long currentTime = System.currentTimeMillis();
        return (currentTime - cacheTime) <= CACHE_DURATION;
    }
    
    /**
     * 获取缓存剩余时间（分钟）
     * @return 缓存剩余时间，如果已过期返回0
     */
    public long getCacheRemainingTime() {
        long cacheTime = sharedPreferences.getLong(KEY_CACHE_TIME, 0);
        long currentTime = System.currentTimeMillis();
        long elapsed = currentTime - cacheTime;
        
        if (elapsed >= CACHE_DURATION) {
            return 0;
        }
        
        return (CACHE_DURATION - elapsed) / (60 * 1000); // 转换为分钟
    }
    
    /**
     * 清除缓存
     */
    public void clearCache() {
        sharedPreferences.edit()
                .remove(KEY_CITY_NAME)
                .remove(KEY_CACHE_TIME)
                .remove(KEY_WEATHER_DATA)
                .apply();
        
        Log.d(TAG, "天气缓存已清除");
    }
    
    /**
     * 将天气信息转换为JSON字符串
     */
    private String convertWeatherToJson(OpenWeatherHelper.WeatherInfo weatherInfo) throws JSONException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("cityName", weatherInfo.cityName != null ? weatherInfo.cityName : "");
        jsonObject.put("temperature", weatherInfo.temperature != null ? weatherInfo.temperature : "");
        jsonObject.put("weatherText", weatherInfo.weatherText != null ? weatherInfo.weatherText : "");
        jsonObject.put("iconCode", weatherInfo.iconCode != null ? weatherInfo.iconCode : "");
        jsonObject.put("windDir", weatherInfo.windDir != null ? weatherInfo.windDir : "");
        jsonObject.put("windSpeed", weatherInfo.windSpeed != null ? weatherInfo.windSpeed : "");
        jsonObject.put("humidity", weatherInfo.humidity != null ? weatherInfo.humidity : "");
        jsonObject.put("pressure", weatherInfo.pressure != null ? weatherInfo.pressure : "");
        jsonObject.put("visibility", weatherInfo.visibility != null ? weatherInfo.visibility : "");
        jsonObject.put("feelsLike", weatherInfo.feelsLike != null ? weatherInfo.feelsLike : "");
        
        return jsonObject.toString();
    }
    
    /**
     * 从JSON字符串解析天气信息
     */
    private OpenWeatherHelper.WeatherInfo parseWeatherFromJson(String jsonString) throws JSONException {
        JSONObject jsonObject = new JSONObject(jsonString);
        
        OpenWeatherHelper.WeatherInfo weatherInfo = new OpenWeatherHelper.WeatherInfo();
        weatherInfo.cityName = jsonObject.optString("cityName", "");
        weatherInfo.temperature = jsonObject.optString("temperature", "");
        weatherInfo.weatherText = jsonObject.optString("weatherText", "");
        weatherInfo.iconCode = jsonObject.optString("iconCode", "");
        weatherInfo.windDir = jsonObject.optString("windDir", "");
        weatherInfo.windSpeed = jsonObject.optString("windSpeed", "");
        weatherInfo.humidity = jsonObject.optString("humidity", "");
        weatherInfo.pressure = jsonObject.optString("pressure", "");
        weatherInfo.visibility = jsonObject.optString("visibility", "");
        weatherInfo.feelsLike = jsonObject.optString("feelsLike", "");
        
        return weatherInfo;
    }
    
    /**
     * 获取缓存状态信息（用于调试）
     */
    public String getCacheStatus() {
        String cachedCityName = sharedPreferences.getString(KEY_CITY_NAME, "无");
        long cacheTime = sharedPreferences.getLong(KEY_CACHE_TIME, 0);
        long remainingTime = getCacheRemainingTime();
        
        return String.format("缓存城市: %s\n缓存时间: %s\n剩余时间: %d分钟", 
                cachedCityName, 
                cacheTime > 0 ? new java.util.Date(cacheTime).toString() : "无",
                remainingTime);
    }
} 